<template>
  <el-form ref="form" :model="form" :rules="rules" label-width="80px">
    <el-form-item label="用户账号">
      <el-input v-model="form.userId" :disabled="true" :readonly="true"></el-input>
    </el-form-item>
    <el-form-item label="用户名称" prop="name">
      <el-input v-model="form.name" placeholder="请输入用户名称"></el-input>
    </el-form-item>
    <el-form-item label="性别">
      <el-radio-group v-model="form.gender" :disabled="true" :readonly="true">
        <el-radio label="男">男</el-radio>
        <el-radio label="女">女</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="系部">
      <el-input v-model="form.department" :disabled="true" :readonly="true"></el-input>
    </el-form-item>
    <el-form-item label="班级">
      <el-input v-model="form.class" :disabled="true" :readonly="true" maxlength="30"
                placeholder="请输入班级"></el-input>
    </el-form-item>
    <el-form-item label="头像" prop="avatarUrl">
      <el-upload
          v-loading="loading"
          :accept="'image/*'"
          :before-upload="beforeUpload"
          :on-change="handleChange"
          :show-file-list="false"
          action="#"
          element-loading-background="rgba(0, 0, 0, 0)"
          element-loading-spinner="el-icon-loading"
          element-loading-text="上传中"
          list-type="picture-card">
        <img v-if="form.avatarUrl" :src="form.avatarUrl" alt="你的头像" style="width: 100%; height: 100%;">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </el-form-item>
    <el-form-item label="角色">
      <el-select v-model="form.role" :disabled="true" placeholder="请选择角色">
        <el-option label="宿管" value="0"></el-option>
        <el-option label="学生" value="1"></el-option>
        <el-option label="管理员" value="3"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="联系方式" prop="contactInfo">
      <el-input v-model="form.contactInfo" maxlength="200" placeholder="请输入联系方式"></el-input>
    </el-form-item>
    <el-form-item label="邮箱地址" prop="email">
      <el-input v-model="form.email" maxlength="200" placeholder="请输入邮箱地址"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit()">提交</el-button>
      <el-button @click="resetForm()">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      form: {
        userId: '',
        name: '',
        gender: '',
        department: '',
        class: '',
        avatarUrl: '',
        role: '0',  // 默认角色为宿管
        contactInfo: '',
        email: '',
      },
      rules: {
        name: [
          {required: true, message: '请输入用户名称', trigger: 'blur'}
        ]
      }
    };
  },
  created() {
    this.getUser();
  },
  mounted() {
    this.form.avatarUrl = this.$store.getters.getUser.avatarUrl;
    this.getUser();
  },
  computed: {
    avatarUrl() {
      return this.$store.getters.getUser.avatarUrl;
    }
  },
  methods: {
    // 根据请求解析token获取用户信息
    getUser() {
      this.$axios.get('/api/users/' + "",
          {
            headers: {
              'token': this.$store.getters.getToken
            }
          })
          .then(response => {
            if (response.data.code === 200) {
              this.form = response.data.data;
              const user = this.$store.getters.getUser;
              user.avatarUrl = this.form.avatarUrl;
              user.name = this.form.name;
              this.$store.dispatch('saveUser', user);
            } else {
              this.$message.error(response.data.msg || '查询用户信息失败');
            }
          })
          .catch(error => {
            console.error('Error fetching users:', error);
          });
    },

    beforeUpload(file) {
      // 取消默认的上传行为
      return false;
    },
    handleChange(file) {
      // 手动触发文件上传
      this.uploadFile(file);
    },
    uploadFile: function (file) {
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.$message.error('上传的图片大小不能超过5MB!');
      } else {
        this.loading = true;
        // 构造自定义的上传请求，包括添加必要的请求头等
        const formData = new FormData();
        formData.append('newAvatar', file.raw);
        // 使用axios发送自定义的文件上传请求
        this.$axios.post('/api/users/updateAvatarByUserId', formData, {
          headers: {
            token: this.$store.getters.getToken,
            // 其他header信息
          }
        }).then(response => {
          this.loading = false;
          if (response.data.code === 200) {
            // 根据上传结果执行相应的处理逻辑
            this.form.avatarUrl = response.data.data;
            const user = this.$store.getters.getUser;
            user.avatarUrl = this.form.avatarUrl;
            this.$store.dispatch('saveUser', user);
            this.$message({message: '修改成功', type: 'success'});
          } else {
            this.$message.error(response.data.msg || '修改头像失败！');
          }
        }).catch(error => {
          // 处理上传失败的情况
          this.loading = false;
          this.$message.error(error || '修改头像失败！');
        });
      }
    },
    onSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$axios.put('/api/users/update', this.form, {
            headers: {
              token: this.$store.getters.getToken,
            }
          }).then(response => {
            this.loading = false;
            if (response.data.code === 200) {
              // 根据上传结果执行相应的处理逻辑
              this.getUser();
              this.$message({message: '修改成功', type: 'success'});
              // 自定义一个事件，使其能够添加成功之后自动隐藏！
              this.$emit('updateBaseSetting');
            } else {
              this.$message.error(response.data.msg || '修改失败！');
            }
          }).catch(error => {
            // 处理上传失败的情况
            this.loading = false;
            this.$message.error(error || '修改失败！');
          });
        } else {
          return false;
        }
      });
    },
    resetForm() {
      this.getUser();
    },

  }
};
</script>
